/**
 * 用户信息模块，包含登录验证的token
 */
import storejs from 'storejs'
import CrossStore from '@/utils/CrossStore'
// import service from '@hedait/service';
// import Vue from 'vue';
// Vue.use(service);

const keys = {
    token: '__TOKEN',
    userInfo: '__USERINFO'
}
const state = {
    access: {
        access_token: ""
    },
    info: null
}

// getters
const getters = {
    getToken: state => {
        return state.access.access_token || storejs.get(keys.token);
    },
    getInfo: state => {
        console.debug('appCenter user getInfo', !!state.info)
        return state.info || storejs.get(keys.userInfo);
    }
}

// actions
const actions = {
    updateToken({ state, commit }, access_token) {
        return new Promise((resolve, reject) => {
            if (state.access.access_token != access_token) {
                CrossStore.setData(keys.token, access_token).then(()=>{
                    commit('updateAccessToken', access_token)
                    storejs.set(keys.token, access_token)
                    resolve(access_token)
                });
            }else{
                resolve(access_token)
            }
        })
    },
    updateInfo({ state, commit }, info) {
        return new Promise((resolve, reject) => {
            CrossStore.setData(keys.userInfo, info).then(()=>{
                storejs.set(keys.userInfo, info)
                commit('updateInfo', info)
                resolve(info)
            });
        })
    }
}

// mutations
const mutations = {
    updateAccessToken(state, access_token) {
        state.access.access_token = access_token
        storejs.set(keys.token, access_token)
    },
    updateInfo(state, info) {
        state.info = info;
        storejs.set(keys.userInfo, info)
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}
